<template>
  <div style="padding:20px">
    <h1>{{id ? '编辑':'新建'}}资讯</h1>
    <el-form label-width = "120px" :rules = "rule" ref = "FormRef" :model = "model">
      <el-form-item label = "【资讯标题】" prop = "title">
        <el-input v-model="model.title" placeholder = "请输入资讯标题" style="width:300px"></el-input>
      </el-form-item>
      <el-form-item label = "【资讯链接】" prop = "url">
        <el-input v-model="model.url" placeholder = "请输入资讯链接" style="width:300px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type = 'primary' @click="save">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: ['id'],
  data () {
    return {
      model: {
        title: '',
        url: ''
      },
      rule: {
        title:
          {
            required: true,
            message: '请填写资讯标题',
            trigger: 'blur'
          },
        url: {
          required: true,
          message: '请填写资讯链接',
          trigger: 'blur'
        }
      }
    }
  },
  methods: {
    async save () {
      this.$refs.FormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.warning('请正确填写所有相关信息')
        }
        const res = this.id ? await this.$http.put('rest/Information', this.model) : await this.$http.post('rest/Information', { ...this.model, _id: this.id })
        if (res.status !== 200) {
          return this.$message.error(this.id ? '修改资讯失败' : '添加资讯失败')
        }
        this.$message.success(this.id ? '修改资讯成功' : '添加资讯成功')
        window.sessionStorage.setItem('activePath', '/information/list')
        this.$router.push('/information/list')
      })
    },
    async fetch () {
      this.$http.get(`rest/Information/${this.id}`).then(res => {
        if (res.status !== 200) {
          window.sessionStorage.setItem('activePath', '/information/list')
          this.$router.push('/information/list')
          return this.$message.error('获取资讯信息失败')
        }
        this.model = res.data
      })
    }
  },
  created () {
    this.id && this.fetch()
  },
  watch: {
    '$route.path': function (newVal) {
      if (newVal === '/information/create') {
        this.$data.model = { ...this.$options.data().model }
      }
    }
  }
}
</script>
